package com.tanhua.controller;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.tanhua.service.userAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
@RestController
@RequestMapping("/system/users/")
public class UserAdminController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private userAdminService userAdminService;
    @GetMapping("verification")
    public void getVerification(@RequestParam("uuid") String uuid, HttpServletResponse response) {

        //生成验证码图片
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 25);

        try {
            ServletOutputStream outputStream = null;
            try {
                outputStream = response.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //图形验证码写出到流
            circleCaptcha.write(outputStream);
            //获取它的字符串验证码
            String code = circleCaptcha.getCode();
            //将字符串验证码保存到redis中
            redisTemplate.opsForValue().set(uuid, code);
            //关闭流
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @PostMapping("login")
    public Map<String, String> login(@RequestBody Map<String, String> param) {
        String username = param.get("username");
        String password = param.get("password");
        String verificationCode = param.get("verificationCode");
        String uuid = param.get("uuid");
        Map<String, String> token = userAdminService.login(username, password, verificationCode, uuid);
        if (token != null) {
            return token;
        }

        return null;
    }
}
